<?php
class ArticleCateController extends BaseManageController{
	/**
	 * 文章分类列表
	 * @param string $parent
	 * @throws CHttpException
	 */
	public function actionAdmin($parent = null){
		$this->pageTitle = '文章分类列表 - ' . Yii::app()->name;
		$tree = ArticleCateModel::getTree();
		$list = $tree->get_formated_list('┊　');
		$this->render('admin', array('tree'=>$list));
	}
	
	/**
	 * 编辑（新增、修改）分类
	 * @param string $id
	 * @param string $parent
	 */
	public function actionEdit($id = null,$parent = null){
		if(Yii::app()->request->isPostRequest){
			$this->_save($id);
		}
		$this->pageTitle = '文章分类编辑 - ' . Yii::app()->name;
		if($id === null){
			$cate = array(
				'_id'			=> '',
				'parent'		=> $parent,
				'tpl_index' 	=> 'index',
				'tpl_list'		=> 'list',
				'tpl_view'		=> 'view',
				'path'			=> '{$id}',
				'name_index'	=> 'index.html',
				'name_list'		=> 'list_{$page}.html',
				'name_view'		=> '{$id}.html',
				'seo_title'		=> '{$cate_name} - {$site_name}',
				'seo_keywords'	=> '{$cate_name},{$site_keywords}',
				'seo_descript'	=> '{$site_desc}',
				'rank'			=> 255,
			);
		}else{
			$mod = new ArticleCateModel();
			$cate = $mod->get_by_key($id);
			if($cate['site_id'] != SITE_ID){
				throw new CHttpException(403, '非法请求！');
			}
		}
		$this->render('edit', array('model'=>$cate));
	}
	
	/**
	 * 保存分类
	 * @param string $id 分类ID
	 */
	private function _save($id){
		if(!isset($_POST['ArticleCate'])){
			$this->ajax_error('非法请求！');
		}
		$cate = $_POST['ArticleCate'];
		$mod = new ArticleCateModel();
		
		if(isset($cate['code']) && !empty($cate['code'])){
			//检查是否有重名的
			$condition = array();
			if(empty($cate['_id'])){
				//新增
				$condition['code'] = $cate['code'];
			}else{
				$condition = array(
					'code' => $cate['code'],
					'_id' => array('$ne'=>$cate['_id'])
				);
			}
			if($mod->exists_attrs($condition)){
				$this->ajax_error('分类代码：“' . $cate['code'] . '”已经存在！');
			}
		}
			
		$cate['rank'] = intval($cate['rank']);
		if(empty($cate['_id'])){
			//新建
			$cate['create_user_id'] = intval(Yii::app()->user->id);
			$cate['create_time'] = time();
			$cate['site_id'] = SITE_ID;
			unset($cate['_id']);
			$mod->insert($cate);
		}else{
			$mod->update_by_key($cate['_id'], $cate);
		}
		ArticleCateModel::cleanCache();
		$this->ajax_info('保存成功！');
	}
}

?>